<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 包邮卡管理
 * Class postalCard
 * @author heyu
 */
class PostalCard extends MY_Controller {

    /**
     * @var ConsumerPostalCardModel
     */
    public $mPostalCard = null;
    /**
     * @var ConsumerUserModel
     */
    public $mConsumer = null;

	public function __construct(){
		parent::__construct();
        $this->loadModel('ConsumerPostalCardModel', 'mPostalCard', 'consumer');
	}
	
	/**
	 * 首页
	 */
	public function index(){
        $data = array(
            'status' => $this->getStatus(),
            'title' => '包邮卡管理'
        );
		$this->view('config/postalCard/home', $data, 'datatable,datepicker');
	}
	
    /**
     * 获取列表数据
     */
    public function getList(){
        $status = (int)get('status');
        $type = (int)get('type');
        $name = trim(get('name'));
        $money = trim(get('money'));
        $useEndDateFrom = strtotime(get('use_end_date_from'));
        $useEndDateTo = strtotime(get('used_time_date_to'));
        $sendDateFrom = strtotime(get('send_date_from'));
        $sendDateTo = strtotime(get('send_date_to'));
        $iSortCol_0 = (int)get('iSortCol_0');//针对某一列进行排序
        $sSortDir_0 = trim(get('sSortDir_0'));//排序方式，值为"asc"或者"desc"

        if ($name){
            $this->db->like(array('name' => $name));
        }
        if ($status){
            $this->db->where(array('status' => $status));
        }
        if ($type){
            $this->db->where(array('type' => $type));
        }
        if ($money){
            $this->db->like(array('money' => $money));
        }
        if($useEndDateFrom){
            $this->db->where('use_end_time >=', $useEndDateFrom);
        }
        if($useEndDateTo){
            $this->db->where('use_end_time <', strtotime('+1day', $useEndDateTo));
        }
        if($sendDateFrom){
            $this->db->where('addtime >=', $sendDateFrom);
        }
        if($sendDateTo){
            $this->db->where('addtime <', strtotime('+1day', $sendDateTo));
        }

        if ($iSortCol_0 == 1){
            $this->db->order_by('money', $sSortDir_0); // 面额
        }else if($iSortCol_0 == 2){
            $this->db->order_by('use_end_time', $sSortDir_0); // 截至时间
        }else if($iSortCol_0 == 3){
            $this->db->order_by('addtime', $sSortDir_0); // 添加时间
        }else{
            $this->db->order_by('addtime desc');
        }

        $this->db->where('status > 1');
        $data = $this->mPostalCard->pagination($this->mPostalCard->tbPostalCard);
        $ids = [];
        foreach ($data['data'] as $k => $v){
            if(!in_array($v['id'], $ids)){
                $ids[] = $v['id'];
            }
        }
        //查询总数量
        $count = $this->mPostalCard->statisticsLogCount($ids);

        foreach ($data['data'] as $k => $v){
            $data['aaData'][$k][] = $v['type'] == 1?'注册发放':"按用户发放";
            $data['aaData'][$k][] = $v['name'];
            $data['aaData'][$k][] = $v['money'];
            $data['aaData'][$k][] = isset($count[$v['id']])?$count[$v['id']]:0;

            $btnConfig = '';
            if ($v['status'] == 2){
                $btnConfig = adminCreateBtn(array(
                    'label' => ' 详情 ',
                    'attr' => array(
                        'href' => getUrl('config/postalCard/details').'?id='.$v['id'],
                        'class' => 'btn btn-xs green-stripe default',
                    ),
                    'tag' => 'a'
                ));
            }
            if ($v['type'] == 1){
                $btnConfig .= adminCreateBtn(array(
                    'label' => ' 修改',
                    'attr' => array(
                        'href' => getUrl('config/postalCard/edit').'?id='.$v['id'],
                        'class' => 'btn btn-xs blue-stripe default',
                    ),
                    'tag' => 'a'
                ));
            }
            $btnConfig .= ' '.adminCreateBtn(array(
                'label' => ' 删除',
                'attr' => array(
                    'href' => getUrl('config/postalCard/deleteBonus').'?id='.$v['id'],
                    'alert-message' => "确认是否删除“ ".$v['name']." ”？",
                    'class' => 'ajax-request-btn btn btn-xs red-stripe default',
                ),
                'tag' => 'a',
                'permissions' => array(
                    'module' => 'config',
                    'key' => 'postalCard-delete'
                )
            ));
            $data['aaData'][$k][] = $btnConfig;
        }
        unset($data['data']);
        echo json_encode($data);
    }

    /**
     * 状态
     * @param null $key
     * @param bool $show
     * @return string
     */
    public function getStatus($key = null, $show = false){
        $config = array(
            '2' => '发布',
            '3' => '未发布',
        );
        if($key === null){
            return $config;
        }

        if($key !== null && ! isset($config[$key])){
            return '';
        }

        if( ! $show ){
            return $config[$key];
        }

        if ($key == 2) {
            return '<span class="label label-success">'.$config[$key].'</span>';
        } else if ($key == 3) {
            return '<span class="label label-danger">' . $config[$key] . '</span>';
        }
    }

    /**
     * 增加/发放包邮卡
     */
    public function add(){
        $data = array(
            'title'=>'添加',
            'add'=>1,
        );

        $this->view('config/postalCard/form', $data, 'datatable,validation,uniform,datepicker');
    }

    /**
     * 编辑
     */
    public function edit(){
        $tA = $this->mPostalCard->getInfo(get('id'));
        if ( ! $tA){
            show_404();
        }
        $data = array(
            'title'=>'编辑',
            'add'=>0,
            'info' => $tA
        );
        $this->view('config/postalCard/form-edit', $data, 'datatable,validation,uniform,datepicker');
    }

    /**
     * 保存数据
     */
    public function save(){
        //表单验证
        $vConf = array(
            array('name', '名称', 'required'),
            array('send_number', '每人发放数量', 'required|is_natural_no_zero'),
            array('money', '面额', 'required')
        );
        $type = (int)post('type');
        $status = (int)post('status');
        $use_date = (int)post('use_date');
        $this->formDataValidation($vConf);

        $id = intval(post('id'));
        $consumerIds = post('consumer_ids');
        $money = post('money');
        $send_number = post('send_number');

        if ($money <= 0){
            $this->ajaxReturn(0, '请选择正确的面额金额');
        }
        if ($money >= 100){
            $this->ajaxReturn(0, '请发放面额小于100的包邮卡');
        }
        $consumerId = array();
        if ($consumerIds){
            $consumerId = explode(',', $consumerIds);
            $sendNumberCount = count($consumerId);
        }

        if ($type==2 and empty($consumerIds)){
            $this->ajaxReturn(0, '请选择用户');
        }

        if (!$use_date or $use_date<=0) {
            $this->ajaxReturn(0, '可用天数不能小于一天');
        }

        $useStartTime = time();
        $useEndTime = strtotime("+".$use_date.' days');

        $time = time();
        $money = floor( $money* 10 ) /10;
        $money = sprintf('%.1f', (float)$money);
        $data = array(
            'name' => trim(post('name')),
            'money' => $money,
            'type' => $type,
            'use_date' => $use_date
        );
        if($type==2){
            $data['use_start_time']=$useStartTime;
            $data['use_end_time']=$useEndTime;
            $data['status']=2;
            $data['surplus_number']=$sendNumberCount*$send_number;
            $data['send_number']=$sendNumberCount*$send_number;
        }
        if($type==1){
            $data['status']=$status;
            $data['send_number']=$send_number;
            $info = $this->mPostalCard->getCard(['type'=>1]);
            if(!empty($info)){
                $id = $info['id'];
            }
        }
        $this->db->trans_begin();
        if (!$id){
            $data['addtime'] = $time;
        }
        if ($id){
            $this->db->where('id', $id);
            $bonusId = $this->mPostalCard->update($this->mPostalCard->tbPostalCard, $data);
        }else{
            $bonusId = $this->mPostalCard->insert($this->mPostalCard->tbPostalCard, $data);
        }

        if (!$bonusId){
            $this->db->trans_rollback();
            $this->ajaxReturn(0, '保存失败');
        }
        $consumerIds = [];
        $msgdata = [];
        $title = '赠送'.$send_number.'张包邮体验券，享免费配送到家.';
        $content = '亲，'.$send_number.'张包邮体验券已存入您的账户，让您尊享生鲜果蔬1小时免费配送到家，请您查收。';
        if($type==2){
            $lData = array();
            foreach ($consumerId as $k => $v){
                if (isset($v) && $v > 0) {
                    for($i = 0 ; $i < $send_number ; $i++ ){
                        $lData[] = array(
                            'postal_card_id' => $bonusId,
                            'type' => $type,
                            'consumer_id' => $v,
                            'order_id' => 0,
                            'money' => $money,
                            'status' => 1,
                            'addtime' => $time,
                            'begintime' => $useStartTime,
                            'userendtime' => $useEndTime,
                        );
                        if(!in_array($v, $consumerIds)){
                            $consumerIds[] = $v;

                            $msgdata[] = array(
                                'consumer_id' => $v,
                                'type' => 2,
                                'title' => $title,
                                'content' => $content,
                                'content_detail' => $content,
                                'addtime' => $time,
                            );
                        }
                    }
                }
            }
            $tA = $this->mPostalCard->insertBatch($this->mPostalCard->tbPostalCardLog, $lData);
            if (!$tA){
                $this->db->trans_rollback();
                $this->ajaxReturn(0, '保存失败');
            }
            $this->loadModel('ConsumerUserModel', 'mConsumer', 'consumer');
            $this->loadModel('ConsumerMessageModel', 'mMessage', 'consumer');
            //获取用户信息
            $this->db->select('jpush_code')
                    ->where_in('id', $consumerIds);

            $jpush = $this->mConsumer->getAll($this->mConsumer->tbUser);
            $tA = $this->mMessage->batchSave($msgdata);
            if (!$tA){
                $this->db->trans_rollback();
                $this->ajaxReturn(0, '推送失败');
            }
            jpush($title, $content, 1, array_column($jpush,'jpush_code'));
        }
        $this->db->trans_commit();
        $this->ajaxReturn(1, '保存成功', NULL, getUrl('config/postalCard'));
    }

    /**
     * 详情
     */
    public function details(){
        $info = $this->mPostalCard->getInfo(get('id'));
        if ( ! $info){
            show_404();
        }
        $data = array(
            'info' => $info,
            'title'=>'详情',
        );
        $this->view('config/postalCard/details', $data, 'datatable,validation,uniform,datepicker');
    }

    /**
     * 获取按用户发放包邮卡详情
     */
    public function getPostalCardLog(){
        $id = (int)get('id');
        $status = (int)get('status');
        $consumer = trim(get('consumer'));
        $mobile = trim(get('mobile'));
        $money = trim(get('money'));
        $orderCode = trim(get('order_code'));
        $code = trim(get('code'));
        $usedTimeDateFrom = strtotime(get('used_time_date_from'));
        $usedTimeDateTo = strtotime(get('used_time_date_to'));
        $sendDateFrom = strtotime(get('send_date_from'));
        $sendDateTo = strtotime(get('send_date_to'));
        $iSortCol_0 = (int)get('iSortCol_0');//针对某一列进行排序
        $sSortDir_0 = trim(get('sSortDir_0'));//排序方式，值为"asc"或者"desc"

        if ($id){
            $this->db->where(array('bl.postal_card_id' => $id));
        }
        if ($status){
            $this->db->where(array('bl.status' => $status));
        }
        if ($consumer){
            $this->db->like(array('u.nickname' => $consumer));
        }
        if ($mobile){
            $this->db->like(array('u.mobile' => $mobile));
        }
        if ($money){
            $this->db->like(array('bl.money' => $money));
        }
        if ($orderCode){
            $this->db->like(array('o.code' => $orderCode));
        }
        if ($code){
            $this->db->like(array('bl.code' => $code));
        }
        if($usedTimeDateFrom){
            $this->db->where('bl.usedtime >=', $usedTimeDateFrom);
        }
        if($usedTimeDateTo){
            $this->db->where('bl.usedtime <', strtotime('+1day', $usedTimeDateTo));
        }
        if($sendDateFrom){
            $this->db->where('bl.userendtime >=', $sendDateFrom);
        }
        if($sendDateTo){
            $this->db->where('bl.userendtime <', strtotime('+1day', $sendDateTo));
        }

        if ($iSortCol_0 == 1){
            $this->db->order_by('bl.money', $sSortDir_0); // 领取金额
        }else if($iSortCol_0 == 4){
            $this->db->order_by('bl.usedtime', $sSortDir_0); // 使用时间
        }else if($iSortCol_0 == 5){
            $this->db->order_by('bl.addtime', $sSortDir_0); // 添加时间
        }else{
            $this->db->order_by('bl.addtime desc');
        }

        $this->db->select('bl.money,bl.status,bl.usedtime,bl.addtime,bl.userendtime,u.nickname as consumer,
            u.mobile as consumer_mobile,o.code as order_code')
            ->join($this->mPostalCard->tbUser.' u', 'u.id=bl.consumer_id')
            ->join($this->mPostalCard->tbOrder.' o', 'o.id=bl.order_id', 'left');

        $data = $this->mPostalCard->pagination($this->mPostalCard->tbPostalCardLog.' bl');
        foreach ($data['data'] as $k => $v){
            $data['aaData'][$k][] = isset($v['consumer']) ? $v['consumer'] : $v['consumer_mobile'];
            $data['aaData'][$k][] =  $v['consumer_mobile'];
            $data['aaData'][$k][] = $v['money'];
            $data['aaData'][$k][] = $v['order_code'];
            $data['aaData'][$k][] = $this->mPostalCard->getLogStatus($v['status'], true);
            $data['aaData'][$k][] = !empty($v['usedtime']) ? dateFormat($v['usedtime']) : '';
            $data['aaData'][$k][] = !empty($v['userendtime']) ?dateFormat($v['userendtime']):'';
            $data['aaData'][$k][] = $this->getStatus($v['status'], true);
            $data['aaData'][$k][] = '';
        }
        unset($data['data']);
        echo json_encode($data);
    }

    /**
     * 修改状态
     */
    public function changeStatus(){
        //表单验证
        $vConf = array(
            array('id', 'id', 'required|is_natural_no_zero'),
        );
        $this->formDataValidation($vConf, array('id' => get('id')));

        $id = (int)get('id');
        $info = $this->mPostalCard->getInfo($id);
        if (!$info){
            $this->ajaxReturn(0, '数据不存在');
        }
        if ($info['type'] == 3 && $info['status'] == 3){
            $this->db->where('id', $id);
            $tA = $this->mPostalCard->update($this->mPostalCard->tbUser, array('status' => 2));
            if (!$tA){
                $this->ajaxReturn(0, '保存失败');
            }
        }
        $this->ajaxReturn(1, '保存成功');
    }

    /**
     * 删除
     */
    public function deleteBonus(){
        //表单验证
        $vConf = array(
            array('id', 'id', 'required|is_natural_no_zero'),
        );
        $this->formDataValidation($vConf, array('id' => get('id')));

        $id = (int)get('id');
        $info = $this->mPostalCard->getInfo($id);
        if (!$info){
            $this->ajaxReturn(0, '包邮卡不存在或已删除');
        }
        if ($info['type'] == 1){
            $this->ajaxReturn(0, '注册赠送包邮卡不能删除');
        }
        if ($info['status'] == 1){
            $this->ajaxReturn(0, '包邮卡已删除');
        }
        $this->db->where('id', $id);
        if ($info['status'] == 3){
            $tA = $this->mPostalCard->delete($this->mPostalCard->tbPostalCard);
            if (!$tA){
                $this->ajaxReturn(0, '删除失败');
            }
        }else if ($info['status'] == 2){
            $tA = $this->mPostalCard->update($this->mPostalCard->tbPostalCard, array('status' => 1));
            if (!$tA){
                $this->ajaxReturn(0, '删除失败');
            }
        }else{
            $this->ajaxReturn(0, '数据错误');
        }
        $this->ajaxReturn(1, '删除成功');
    }

    /**
     * 获取用户列表
     */
    public function getConsumerList(){

        $iSortCol_0 = (int)get('iSortCol_0');

        if($iSortCol_0==5){
            $_GET['iSortCol_0']=6;
        }
        if($iSortCol_0==6){
            $_GET['iSortCol_0']=7;
        }

        $this->loadModel('ConsumerUserModel', 'mConsumer', 'consumer');
        $data = $this->mConsumer->adminGetList();
        foreach ($data['data'] as $k => $v){
            $img = isset($v['portrait']) ? getImage($v['portrait'], 'xs') : getDefaultPortrait();
            $data['aaData'][$k][] = '<input type="checkbox" class="checkboxes" name="consumer_id[]" value="' . $v['id'] .'">';
            $data['aaData'][$k][] = '<img src="'.$img.'" class="portrait img-wh"/>';
            $data['aaData'][$k][] = $v['realname'];
            $data['aaData'][$k][] = $v['nickname'];
            $data['aaData'][$k][] = $v['mobile'];
            $data['aaData'][$k][] = isset($v['addtime']) ? dateFormat($v['addtime']) : '';
            $data['aaData'][$k][] = isset($v['last_login_time']) ? dateFormat($v['last_login_time']) : '';
            $data['aaData'][$k][] = $this->adminStatus($v['status'], true);
            $data['aaData'][$k][] = '';
        }
        unset($data['data']);
        echo json_encode($data);
    }

    public function getRegistPostCard(){
        $info = $this->mPostalCard->getCard(['type'=>1]);
        $this->ajaxReturn(1, '已获取',$info);
    }

}
